package com.topisv.tms.web.stock.history;


import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.WritableSheet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.stock.history.InvHistory;
import com.topisv.tms.service.stock.history.InvHistoryService;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.tools.ExcelUtils2;
import com.topisv.tms.web.base.BaseDataTableController;

@Controller
@RequestMapping(value = "/invHistory")
public class InvHistoryController extends BaseDataTableController{
	
	private static final Logger logger = LoggerFactory.getLogger(InvHistoryController.class);
	
	@Autowired
	private InvHistoryService invHistoryService;
	
	@RequestMapping(value = "v2_query",method = RequestMethod.GET)
	public String queryInit(Model model, ServletRequest request, ServletResponse response) throws Exception{
		fillSelectValue(model,null);
		return "stock/history/invHistory";
	}
	
	@RequestMapping(value = "query")
	public void query(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) throws Exception{
		try {
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			Map<String, Object> param = paramHolder.getSearchParams();
			String customer = (String)param.get("customerCode");
			String warehouse = (String)param.get("warehouseCode");
			String sku = (String)param.get("sku");
			String fromDate=(String)param.get("fromDate");
			
			param.put("fromDate", fromDate);
			param.put("customer", customer);
			param.put("warehouse", warehouse);
			param.put("sku", sku);
			Page<InvHistory> page = this.invHistoryService.loadPageByParam(paramHolder.getSearchParams(),paramHolder.getCurPage(), paramHolder.getPageSize());
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			logger.error("error",e);
		}
	}
	
	@RequestMapping(value = "v2_toQuery")
	public String toUlorderMgrPagee(Model model, ServletRequest request) {
		try {
			fillSelectValue(model,null);
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "stock/history/invHistory";
	}
	
	/**
	 * 导出快递清单
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "exportExcel")
	public String exportExcel(ServletRequest request, HttpServletResponse response) throws Exception {
		FileInputStream f=null;
		OutputStream output=null;
		try{
		Date now=new Date();
		DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
		String customer = (String)searchParams.get("customerCode");
		String warehouse = (String)searchParams.get("warehouseCode");
		String sku = (String)searchParams.get("sku");
		String fromDate = (String)searchParams.get("fromDate");
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("customer", customer);
		param.put("warehouse", warehouse);
		param.put("sku", sku);
		param.put("fromDate", fromDate);
		List<InvHistory> invHistoryList =  this.invHistoryService.load(param);
		List<Object[]> rs = new ArrayList<Object[]>();
/*		int salesNum;
		int orderNum;
		int outNum;
		int inNum;*/
		for(InvHistory invHistory:invHistoryList){	      
			     /* if(invHistory.getSalesNum() != null){
				      salesNum = invHistory.getSalesNum();
			      }else{
			    	  salesNum = 0;
			      }
			      if(invHistory.getOrderNum() != null){
			    	  orderNum = invHistory.getOrderNum();
			      }else{
			    	  orderNum = 0;
			      }
			      if(invHistory.getOutNum() != null){
			    	  outNum = invHistory.getOutNum();
			      }else{
			    	  outNum = 0;
			      }
			      if(invHistory.getInNum() != null){
			    	  inNum = invHistory.getInNum();
			      }else{
			    	  inNum = 0;
			      }*/
				  Object[] object = {
							    invHistory.getCustomer().getCustomerName(),
								invHistory.getWarehouse().getGroupName(),
								invHistory.getInvDate(),
								invHistory.getSku(),
								invHistory.getSkuName(),
								invHistory.getSalesNum() + invHistory.getOrderNum() + invHistory.getOutNum() + invHistory.getInNum(),
								invHistory.getInNum(),
								invHistory.getOutNum(),
								invHistory.getAdjustNum(),
								invHistory.getSalesNum() + invHistory.getOrderNum(),
								null
					};
					rs.add(object);
				}
		String[] title = {"客户编码","仓库编码","日期","商品编码","商品名称","期初库存","本期入","本期出","本期调整","期末库存"};
		String filepath = customer + "_" + warehouse + "进出存报表.xls";
		String title_page = "进出存报表";
		ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , rs);
		((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
		f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
		byte[] fb = new byte[f.available()];
		f.read(fb);
		ByteArrayInputStream bais = new ByteArrayInputStream(fb);
		output =((HttpServletResponse)response).getOutputStream();
		int by = 0;
		while ((by = bais.read()) != -1) {
			output.write(by);
		}
		output.flush();
        logger.info("=======导出结束=======");

		}catch (Exception e) {
		    e.printStackTrace();
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		
		return null;
	}
}
